package com.ruoyi.common.utils;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: TODO
 * @Author ONESTAR
 * @Date: 2021/7/19 16:40
 * @Version 1.0
 */
public class JsapiTicketUtil {

    private static Logger logger = LoggerFactory.getLogger("sys-wx");

    /***
     * 模拟get请求
     * @param url
     * @param charset
     * @param timeout
     * @return
     */
    public static String sendGet(String url, String charset, int timeout)
    {
        String result = "";
        try
        {
            URL u = new URL(url);
            try
            {
                URLConnection conn = u.openConnection();
                conn.connect();
                conn.setConnectTimeout(timeout);
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                String line="";
                while ((line = in.readLine()) != null)
                {

                    result = result + line;
                }
                in.close();
            } catch (IOException e) {
                return result;
            }
        }
        catch (MalformedURLException e)
        {
            return result;
        }

        return result;
    }
//    public static String getAccessToken() throws IOException{
//
//
//
//        String appid=AuthUtil.APPID;//应用ID
//        String appSecret=AuthUtil.APPSECRET;//(应用密钥)
//        String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+"";
//        String result = HttpClientHelper.doGet(url);
//        JSONObject resultJson = JSONObject.fromObject(result);
//        String accessToken = "";
//        if(resultJson.has("access_token")){
//            accessToken = resultJson.get("access_token").toString();
//        }else{
//            // accessToken过期,重新调用一次
//            String res = HttpClientHelper.doGet(url);
//            JSONObject resJson = JSONObject.fromObject(res);
//            accessToken = resJson.get("access_token").toString();
//        }
//        return accessToken;
//    }

//    public static String getJSApiTicket(String acessToken) throws IOException{
//        //获取token
//        String acess_token= JsapiTicketUtil.getAccessToken();
//        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi";
//        String backData=HttpClientHelper.doGet(urlStr);
//        logger.info("材料员界面 -> 扫一扫初始化 -> 获取backData:" + backData);
//        String ticket = (String) JSONObject.fromObject(backData).get("ticket");
//        logger.info("材料员界面 -> 扫一扫初始化 -> ticket:" + ticket);
//        return  ticket;
//    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {


        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        logger.info("getSign() getSign:{} url", url);
        logger.info("getSign() getSign:{} jsapi_ticket", jsapi_ticket);
        logger.info("getSign() getSign:{} nonceStr", nonce_str);
        logger.info("getSign() getSign:{} timestamp", timestamp);
        logger.info("getSign() getSign:{} signature", signature);
        return ret;
    }


    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
